package com.linhh.convert.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lhh
 * @Date 2024-12-17-43 11:43
 */
public class CsvUtil {
    public CsvUtil(){}

    public static List<List<String>> readCSVFileData(String filePath){
        BufferedReader reader = null;
        List<List<String>> dataList = new ArrayList();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"utf-8"));
        }catch (Exception var){
            var.printStackTrace();
        }
        try {
            String line = null;
            for(int lineNum = 0;(line = reader.readLine())!= null;++lineNum){
                if (lineNum !=0){
                    line = line +  ",";
                    Pattern pCells = Pattern.compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,");
                    Matcher mCells = pCells.matcher(line);
                    List<String> cells = new LinkedList();

                    while(mCells.find()){
                        String str = mCells.group();
                        str = str.replaceAll("(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,","$1");
                        str = str.replaceAll("(?sm)(\"(\"))","$2");
                        cells.add(str);
                    }
                    dataList.add(cells);
                }
            }

        }catch (Exception var2){
            var2.printStackTrace();
        }finally {
            try {
                if (reader != null){
                    reader.close();
                }
            }catch (IOException var3){
                var3.printStackTrace();
            }
        }
        return dataList;
    }

    public static void writeCSVFileData(String filePath,List<List<String>> dataList){
        BufferedWriter bw = null;
        try{
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath,true),"GBK"));
            for (int i=0;i<dataList.size();i++)
            {
                bw.write((String)((List)dataList.get(i)).get(0)+","+ (String)((List)dataList.get(i)).get(1));
                bw.newLine();
            }
        }catch (FileNotFoundException e){
            System.out.println(e);
            e.printStackTrace();
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(bw !=null){
                    bw.flush();
                    bw.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
